//
//  CommunityManageController.m
//  QRMaster
//
//  Created by myApple on 16/4/26.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "CommunityManageController.h"
#import "CommunityManageCell.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "OpertionPlist.h"
#import "checkPower.h"
#import "CommunityInfoLogic.h"
#import "communityModel.h"
#import "setLockPwdViewController.h"
#import "SetLockViewController.h"
#import "DatePickerViewController.h"
#import "ManagerShareCardController.h"
#import "QRSingleton.h"
#import "CommunityInfoModel.h"
#import "MJExtension.h"
#import "BackTableViewCell.h"
#import "selectCommunityController.h"
#import "CommunityListModel.h"
#import "AuthenticateCommunityViewController.h"

#import "ManagerTodayShareCardViewController.h"

@interface CommunityManageController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
{
    UITableView * communityManageTableView;
    NSArray * titleArray;
    UILabel * communityNameLabel;
    UILabel * authenLabel;
    UIImageView * authenImageView;
    NSString * authenType;
}

@end

@implementation CommunityManageController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"communityManage", nil);
    // Do any additional setup after loading the view.
    titleArray = @[NSLocalizedString(@"lockPwdSetting", nil),NSLocalizedString(@"lockSetting", nil),NSLocalizedString(@"communityShareList", nil),NSLocalizedString(@"communityTime", nil)];
    [self prepareSectionView];
    [self prepareTableView];
    [self getCommunityInfo];
}

-(void)prepareTableView
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT - 64;
    communityManageTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    communityManageTableView.delegate = self;
    communityManageTableView.dataSource = self;
    communityManageTableView.tableFooterView = [[UIView alloc]init];
    communityManageTableView.backgroundColor = UIColorFromRGB(0xebebeb);
    [self.view addSubview:communityManageTableView];
    
}

-(void)prepareSectionView
{
    float x = 22;
    float y = (68 - 20) / 2.0;
    float width = UI_SCREEN_WIDTH / 2.0 - x;
    float height = 20;
    
    communityNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    communityNameLabel.font = [UIFont systemFontOfSize:16.0];
    communityNameLabel.textColor = UIColorFromRGB(0x333333);
    communityNameLabel.numberOfLines = 3;
    
    x = UI_SCREEN_WIDTH / 2.0;
    y = (68 - 16) / 2.0;
    width = 14;
    height = 16;
    authenImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    authenImageView.image = [UIImage imageNamed:@"authenImage"];
    
    x = UI_SCREEN_WIDTH - 40;
    y = (68 - 20)/2.0;
    width = UI_SCREEN_WIDTH / 2.0 - 40 - 28;
    height = 20;
    authenLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    authenLabel.font =[UIFont systemFontOfSize:15.0];
  //  authenLabel.textColor = UIColorFromRGB(0xff0000);
    authenLabel.textAlignment = NSTextAlignmentRight;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else
    {
        return 2;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 68.0;
    }
    else
    {
        return 56.0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 16.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString  * identityCell = @"cellId";
    CommunityManageCell * cell = [tableView dequeueReusableCellWithIdentifier:identityCell];
    if (!cell) {
        cell = [[CommunityManageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identityCell];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (indexPath.section == 0) {
        communityNameLabel.text = [QRSingleton sharedQRSingleton].communityName;
        [cell.contentView addSubview:communityNameLabel];
        [cell.contentView addSubview:authenImageView];
        // authenLabel.text = authenType;
        [cell.contentView addSubview:authenLabel];
        [self calculateHeight:communityNameLabel.text];
        [self calculateWidth:authenLabel.text];
    }
    else
    {
        cell.titleString = titleArray[(indexPath.section - 1) * 2 + indexPath.row];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        [self authen];
    }
    else if (indexPath.section == 1)
    {
        if (indexPath.row == 0) {
            [self setLockPwd];
        }
        else
        {
            [self setLock];
        }
    }
    else
    {
        if (indexPath.row == 0) {
            [self shareCard];
        }
        else
        {
            [self setTime];
        }
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark -------- 认证
-(void)authen
{
    AuthenticateCommunityViewController * acvc = [[AuthenticateCommunityViewController alloc]init];
    acvc.hidesBottomBarWhenPushed = YES;
    acvc.communityStyle = authenType;
    acvc.status = ^(NSInteger status)
    {
        [self showAuthenStatus:status];
    };
    [self.navigationController pushViewController:acvc animated:YES];
}

#pragma mark ----------- 门锁设置
-(void)setLock
{
    UIAlertView * alter = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"lockSetting", @"门锁设置") message:NSLocalizedString(@"goToSetLock", @"进入门锁设置")delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel", @"门锁设置") otherButtonTitles:NSLocalizedString(@"alterSure", @"门锁设置"), nil];
    [alter show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        SetLockViewController * sckc = [[SetLockViewController alloc]init];
        sckc.hidesBottomBarWhenPushed = YES;
        sckc.communityId = [QRSingleton sharedQRSingleton].communityId;
        [self.navigationController pushViewController:sckc animated:YES];
    }
}


#pragma mark ------------ 密钥设置
-(void)setLockPwd
{
    setLockPwdViewController * slpv = [[setLockPwdViewController alloc]init];
    slpv.communityId = [QRSingleton sharedQRSingleton].communityId;
    slpv.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:slpv animated:YES];
}


#pragma mark ----------- 开门周期设置
-(void)setTime
{
    DatePickerViewController * spvc = [[DatePickerViewController alloc]init];
    spvc.communityId = [QRSingleton sharedQRSingleton].communityId;
    spvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:spvc animated:YES];
}

#pragma mark ------------分享记录
-(void)shareCard
{
//    ManagerShareCardController * mscc = [[ManagerShareCardController alloc]init];
    ManagerTodayShareCardViewController * mscc = [[ManagerTodayShareCardViewController alloc] init];
    mscc.communityId = [QRSingleton sharedQRSingleton].communityId;
    mscc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mscc animated:YES];
}

#pragma mark ------------ 请求集群信息
-(void)getCommunityInfo
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:UID forKey:@"id"];
    [postDict setValue:TOKEN forKey:@"token"];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(NEWCOMMUNITYINFO) params:postDict block:^(id downLoadData, id error) {
        [self stopWaiting];
        NSDictionary * data = [downLoadData objectForKey:@"data"];
        if (data) {
            authenType = [data objectForKey:@"type"];
             [QRSingleton sharedQRSingleton].timeStatus = [[data objectForKey:@"timeStatus"]integerValue] == 1?YES:NO;
            [self showAuthenStatus:[[data objectForKey:@"authStatus"]integerValue]];
            CommunityInfoModel * model = [CommunityInfoModel mj_objectWithKeyValues:data];
            CommunityInfoLogic * comDataBase = [[CommunityInfoLogic alloc]init];
            [comDataBase deleteCommunityInfo:[QRSingleton sharedQRSingleton].communityId];
            [comDataBase insertCommunityData:model withCommuntiyId:[QRSingleton sharedQRSingleton].communityId member_timestamp:nil customer_timestamp:nil group_timestamp:nil room_timestamp:nil];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        [communityManageTableView reloadData];
    }];
}


#pragma mark -------------- 根据状态来显示认证和图片
-(void)showAuthenStatus:(NSInteger)statu
{
    switch (statu) {
        case 0:
            authenLabel.text = NSLocalizedString(@"notAuthen", @"未认证");
            authenImageView.image = [UIImage imageNamed:@"UnAuthenImage"];
            authenLabel.textColor = UIColorFromRGB(0xff0000);
            break;
        case 1:
            authenLabel.text = NSLocalizedString(@"needVerify", @"认证中");
            authenImageView.image = [UIImage imageNamed:@"UnAuthenImage"];
            authenLabel.textColor = UIColorFromRGB(0xff0000);
            break;
        case 2:
            authenLabel.text = NSLocalizedString(@"authenicate", @"已认证");
            authenImageView.image = [UIImage imageNamed:@"authenImage"];
            authenLabel.textColor = UIColorFromRGB(0x00aff0);
            break;
        case 3:
            authenLabel.text = NSLocalizedString(@"authenicate", @"已认证");
            authenImageView.image = [UIImage imageNamed:@"authenImage"];
            authenLabel.textColor = UIColorFromRGB(0x00aff0);
            break;
        default:
            authenLabel.text = NSLocalizedString(@"authenfalse", @"认证失败");
            authenImageView.image = [UIImage imageNamed:@"authenImage"];
            authenLabel.textColor = UIColorFromRGB(0xff0000);
            break;
    }
    [communityManageTableView reloadData];
}

#pragma mark ---------- 集群标题的高
-(void)calculateHeight:(NSString *)str
{
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16.0],};
    CGSize textSize = [str boundingRectWithSize:CGSizeMake(communityNameLabel.frame.size.width, 1000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
    if (textSize.height > 60) {
         communityNameLabel.frame = CGRectMake(communityNameLabel.frame.origin.x, 4, communityNameLabel.frame.size.width, 60);
    }
    else
    {
         communityNameLabel.frame = CGRectMake(communityNameLabel.frame.origin.x, (68 - textSize.height) / 2.0, communityNameLabel.frame.size.width, textSize.height);
    }
    [communityNameLabel sizeToFit];
}


#pragma mark ----------  认证的宽
-(void)calculateWidth:(NSString *)str
{
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:15.0],};
    CGSize textSize = [str boundingRectWithSize:CGSizeMake(1000, 20) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
    authenLabel.frame = CGRectMake(UI_SCREEN_WIDTH - 40 - textSize.width, authenLabel.frame.origin.y, textSize.width, authenLabel.frame.size.height);
    authenImageView.frame = CGRectMake(authenLabel.frame.origin.x - 10 - authenImageView.frame.size.width, authenImageView.frame.origin.y, authenImageView.frame.size.width, authenImageView.frame.size.height);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
